﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;

namespace dpruna.SharePoint
{
    public class ExtendedLookupFieldControl : BaseFieldControl
    {
        #region Controls
        protected TextBox extendedLookupTextBox;
        protected Image extendedLookupImage;
        protected HiddenField extendedLookupValue;
        #endregion

        #region Fields
        private int queryStringValue;
        #endregion

        #region Properties
        protected string ClientSideInstanceName
        {
            get
            {
                string clientSideInstanceName = String.Concat("ml_", this.FieldName);
                return clientSideInstanceName;
            }
        }
        protected override string DefaultTemplateName
        {
            get
            {
                if (this.ControlMode == SPControlMode.Display)
                    return this.DisplayTemplateName;
                else
                    return "ExtendedLookupRenderingTemplate";
            }
        }

        protected bool IsQueryStringFiltered
        {
            get
            {
                return !String.IsNullOrEmpty(this.Page.Request[this.FieldName]);
            }
        }
        public override object Value
        {
            get
            {
                if (ExtendedLookupField.AllowMultipleValues &&
                    !
                    String.IsNullOrEmpty(extendedLookupValue.Value))
                {
                    return new SPFieldLookupValueCollection(extendedLookupValue.Value.ToSPFieldLookupValueCollectionString());
                }
                else
                {
                    int idValue = 0;
                    if (extendedLookupValue != null &&
                        !String.IsNullOrEmpty(extendedLookupValue.Value) &&
                        int.TryParse(extendedLookupValue.Value, out idValue))
                    {
                        return new SPFieldLookupValue(idValue, extendedLookupTextBox.Text);
                    }
                }

                return null;
            }
            set
            {
                if (ExtendedLookupField.AllowMultipleValues)
                {
                    SPFieldLookupValueCollection lkpValueCollection = (SPFieldLookupValueCollection)this.ItemFieldValue;
                    extendedLookupValue.Value = lkpValueCollection.ToSemicolumnSeparatedLookupIds();
                    extendedLookupTextBox.Text = lkpValueCollection.ToSemicolumnSeparatedLookupValues();
                }
                else
                {
                    SPFieldLookupValue lkpValue = (SPFieldLookupValue)this.ItemFieldValue;
                    extendedLookupValue.Value = lkpValue.LookupId.ToString();
                    extendedLookupTextBox.Text = lkpValue.LookupValue;
                }
            }
        }
        public ExtendedLookup ExtendedLookupField
        {
            get
            {
                return (ExtendedLookup)Field;
            }
        }
        protected virtual int QueryStringValue
        {
            get
            {
                string queryStringValueString = this.Page.Request[Field.InternalName];
                if (!
                    String.IsNullOrEmpty(queryStringValueString) &&
                    int.TryParse(queryStringValueString, out queryStringValue))
                {
                    return queryStringValue;
                }
                return 0;
            }
        }
        #endregion

        #region Protected Methods
        protected override void OnInit(EventArgs e)
        {
            this.EnsureChildControls();
            base.OnInit(e);
            if (IsQueryStringFiltered)
            {
                SPFieldLookupValue fieldValue = this.ItemFieldValue as SPFieldLookupValue;
                if (fieldValue != null && fieldValue.LookupId == QueryStringValue)
                {
                    extendedLookupValue.Value = fieldValue.LookupId.ToString();
                    extendedLookupTextBox.Text = fieldValue.LookupValue;
                }
                else if (QueryStringValue > 0)
                {
                    SPWeb lookupWeb = GetLookupWeb(ExtendedLookupField.LookupWebId);
                    Guid lookupListId;
                    if (lookupWeb != null &&
                        Helpers.TryParseGuid(ExtendedLookupField.LookupList, out lookupListId))
                    {
                        SPList lookupList = lookupWeb.Lists.OfType<SPList>().FirstOrDefault(s => s.ID == lookupListId);
                        SPListItem lookupItem = lookupList.GetItemByIdSelectedFields(QueryStringValue, "ID", ExtendedLookupField.LookupField);
                        extendedLookupTextBox.Text = (string)lookupItem[ExtendedLookupField.LookupField];
                        extendedLookupValue.Value = lookupItem.ID.ToString();
                        if (lookupWeb.ID != Web.ID)
                            lookupWeb.Dispose();
                    }
                    else
                    {
                        //
                        // TODO: Log this to ULS: String.Format("Web with id {0} not found for master lookup field {1} ({2})", ExtendedLookupField.LookupWebId, ExtendedLookupField.Title, ExtendedLookupField.InternalName));
                        //    
                    }
                }
            }
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (this.ControlMode == SPControlMode.Display)
                return;

            extendedLookupValue = (HiddenField)this.TemplateContainer.FindControl("extendedLookupValue");
            extendedLookupValue.ID = "ml_value";

            extendedLookupTextBox = (TextBox)this.TemplateContainer.FindControl("extendedLookupTextBox");
            extendedLookupTextBox.Attributes.Add("title", Field.InternalName);
            extendedLookupTextBox.ReadOnly = true;

            extendedLookupImage = (Image)this.TemplateContainer.FindControl("extendedLookupImage");

            string lookupPageUrl =
                ExtendedLookupField.SearchPageURL +
                String.Format("?List={0}&Field={1}&TextElem={2}&ValElem={3}&MultiSelect={4}",
                    ((ExtendedLookup)this.Field).LookupList,
                    ((ExtendedLookup)this.Field).LookupField,
                    extendedLookupTextBox.ClientID,
                    extendedLookupValue.ClientID,
                    ((ExtendedLookup)this.Field).AllowMultipleValues ? 1 : 0);
            lookupPageUrl = String.Concat(Web.Url, lookupPageUrl);
            var lookupWeb = GetLookupWeb(ExtendedLookupField.LookupWebId);
            string popupTitle = "Lookup {0} item(s)";
            Guid lookupListId;
            if (lookupWeb != null &&
                Helpers.TryParseGuid(ExtendedLookupField.LookupList, out lookupListId))
            {
                SPList lookupList = lookupWeb.Lists.OfType<SPList>().FirstOrDefault(s => s.ID == lookupListId);
                popupTitle = String.Format(popupTitle, lookupList.Title);
            }
            else
                popupTitle = "Lookup item(s)";

            extendedLookupImage.Attributes.Add("title", Field.InternalName);
            if (!
                IsQueryStringFiltered)
            {
                extendedLookupImage.Attributes.Add("onmouseout", "this.src='\u002f_layouts\u002fimages\u002fgosearch15.png'");
                extendedLookupImage.Attributes.Add("onmouseover", "this.src='\u002f_layouts\u002fimages\u002fgosearchhover15.png'");
                extendedLookupImage.Attributes.Add("onclick",
                    String.Format("var options = SP.UI.$create_DialogOptions();options.url = '{0}'; options.title = '{1}'; SP.UI.ModalDialog.showModalDialog(options);", lookupPageUrl, popupTitle));
            }
        }
        protected virtual SPWeb GetLookupWeb(Guid webId)
        {
            if (Web.ID == webId || webId == Guid.Empty)
                return Web;

            return Web.Site.AllWebs.OfType<SPWeb>().FirstOrDefault(s => s.ID == webId);
        }
        #endregion
    }
}
